package rsa

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"io/ioutil"
)

// Encrypt 加密
func Encrypt(plainText []byte, pubKey []byte) ([]byte, error) {
	// pem 解码
	block, _ := pem.Decode(pubKey)

	// x509 解码
	publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	// 类型断言
	publicKey := publicKeyInterface.(*rsa.PublicKey)

	// 对明文进行加密
	return rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
}

// EncryptByKeyFile 加密，通过密钥文件
func EncryptByKeyFile(plainText []byte, pubKeyFilename string) ([]byte, error) {
	pubKey, err := ioutil.ReadFile(pubKeyFilename)
	if err != nil {
		return nil, err
	}
	return Encrypt(plainText, pubKey)
}

// Decrypt 解密
func Decrypt(cipherText []byte, priKey []byte) ([]byte, error) {
	// pem解码
	block, _ := pem.Decode(priKey)

	// X509解码
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	// 对密文进行解密
	return rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
}

// DecryptByKeyFile 解密，通过密钥文件
func DecryptByKeyFile(cipherText []byte, priKeyFilename string) ([]byte, error) {
	priKey, err := ioutil.ReadFile(priKeyFilename)
	if err != nil {
		return nil, err
	}
	return Decrypt(cipherText, priKey)
}
